package xyz.xpman.prisonerfitness.util;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unused")
public class XmlToMapHandler extends DefaultHandler {
    private static final int MIN_DEEP = 1;
    private static final int MAX_DEEP = 2;
    private static final String UNIQUE_KEY = "id";
    private static final String startElementName = "data";

    private int deep = 0;
    private String tagName = null;
    private final Map<String, String> data = new HashMap<>();



    /**
     * 开始处理节点,在这里获得节点属性值的（节点属性）
     * @param uri url
     * @param localName name
     * @param qName qName
     * @param attributes  attributes
     * @throws SAXException SAXException
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        deep++;

        if (MIN_DEEP <= deep && deep <= MAX_DEEP) {

            if (MIN_DEEP == deep &&  localName.equals(startElementName)) {
                data.put(UNIQUE_KEY, attributes.getValue(UNIQUE_KEY));
            }

            // 只处理第一层和第二层
            this.tagName = localName;
            super.startElement(uri, localName, qName, attributes);
        }
    }

    // 处理没有属性的节点（节点内容）
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        if (StrKit.notBlank(tagName) && MAX_DEEP == deep) {
            data.put(tagName, new String(ch, start, length));
        }
        super.characters(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (MIN_DEEP <= deep && deep <= MAX_DEEP) {
            super.endElement(uri, localName, qName);
            deep--;
        }
    }

    public Map<String, String> getData() {
        return data;
    }

}
